package com.dao;
import java.text.SimpleDateFormat;
import java.util.List;

import com.beans.OrderGoods;
import com.beans.OrderInfo;
import com.jdbc.DBUtil;
import com.utils.PageInfo;
import com.utils.StrUtil;

//订单管理
public class OrderDao {
	//发货(改变订单状态,同时更新发货日期)
	public int sendGoods(int orderId,String state){
		String sendDate=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new java.util.Date());
		String sql="update orderInfo set orderState=?,sendDate=? where id=? ";
		return DBUtil.update(sql, state,sendDate,orderId);
	}
	
	//多条件查询订单数量
	public int getOrderCount(String orderNo, String orderState,String beginDate, String endDate) {
		String sql="select count(*) from orderInfo where 1=1 ";
		
		if(!StrUtil.isNullOrEmpty(orderNo)){
			sql+=" and  orderNo='"+ orderNo +"'";
		}
		
		if(!StrUtil.isNullOrEmpty(orderState)){
			sql+=" and  orderState='"+ orderState +"'";
		}
		
		if(!StrUtil.isNullOrEmpty(beginDate)){
			sql+=" and  orderDate>='"+ beginDate +"'";
		}
		if(!StrUtil.isNullOrEmpty(endDate)){
			sql+=" and  orderDate <='"+ endDate +" 23:59:59'";
		}
		
		Long result=DBUtil.getScalar(sql);   
		return new Integer(result+"");  //因为 上面的 getScalar 实际返回的是long型,而方法的返回值是int型,所以要转换一下
	}

	//多条件分页查询订单列表
	public List<OrderInfo> getOrderList(String orderNo, String orderState,String beginDate,
			String endDate, PageInfo page) {
		String sql="select * from orderInfo where 1=1 "; 
		
		if(!StrUtil.isNullOrEmpty(orderNo)){
			sql+=" and  orderNo='"+ orderNo +"'";
		}
		
		if(!StrUtil.isNullOrEmpty(orderState)){
			sql+=" and  orderState='"+ orderState +"'";
		}

		if(!StrUtil.isNullOrEmpty(beginDate)){
			sql+=" and  orderDate >='"+ beginDate +"'";
		}
		if(!StrUtil.isNullOrEmpty(endDate)){
			sql+=" and  orderDate <='"+ endDate +"  23:59:59'";
		}
		
		sql+=" order by editDate desc limit ?,? "; 
		
		return DBUtil.getList(sql, OrderInfo.class, page.getBeginRow(),page.getPageSize());
	}

	//根据订单号,查询订单信息
	public OrderInfo getOrderById(int orderId) {
		String sql="select a.*,b.memberNO as memberNO  from orderInfo a left join memberInfo b on a.memberId=b.id  where a.id= ? "; 
		return DBUtil.getOneObject(sql, OrderInfo.class, orderId);
	}

	//根据订单id,查询订单对应的商品信息
	public List<OrderGoods> getGoodslist(int orderId) {
		String sql="select * from orderGoods where orderId=? ";
		return DBUtil.getList(sql, OrderGoods.class, orderId);
	}

	//删除订单
	public void deleteOrder(int orderId) {
		//先删除除该订单对应的商品
		DBUtil.update("delete from orderGoods where orderId=?", orderId);
		
		//再删除订单表
		DBUtil.update("delete from orderInfo where id=?", orderId);	
	}

}
